#include <iostream>
#include <memory>
#include "UDP.hpp"

// ./client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "指令错误" << std::endl;
        exit(FAIL);
    }

    std::string ip = argv[1];
    int port = std::stoi(argv[2]);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "创建套接字失败" << std::endl;
        exit(FAIL);
    }
    std::cout << "创建套接字成功" << std::endl;

    // 读写
    while (true)
    {
        // 发送消息
        std::cout << "Enter #";
        std::string enter;
        std::getline(std::cin, enter);
        sockaddr_in send_addr;
        send_addr.sin_family = AF_INET;
        send_addr.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &send_addr.sin_addr);
        socklen_t len = sizeof(send_addr);
        ssize_t n = sendto(sockfd, enter.c_str(), enter.size(), 0, (struct sockaddr *)&send_addr, len);
        if (n < 0)
        {
            std::cout << "发送异常" << std::endl;
            exit(FAIL);
        }
        std::cout << "发送成功" << std::endl;
        // 接收消息
        char buffer[1024];
        sockaddr_in addr;
        socklen_t length;
        ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&addr, &length);
        if (m > 0)
        {
            buffer[n] = 0;
            std::cout << "接收成功: " << buffer << std::endl;
        }
        else if (m == 0)
        {
            std::cout << "recvfrom 被关闭" << std::endl;
            exit(SUCCESS);
        }
        else
        {
            std::cout << "接收异常" << std::endl;
            exit(FAIL);
        }
    }
    return 0;
}